import os
import datetime
import time
import sys 
from fabric.context_managers import *
from fabric.contrib.console import confirm
from fabric.colors import *
from fabric.api  import *
#本地开发服务器信息
env.local_package_dir='D:/software'
env.time=time.strftime("%Y%m%d")
env.local_bakcup_dir='/tmp'
env.local_package_name='python-3.6.3-amd64.exe'

#远程服务器信息
#env.hosts=['192.168.1.190','192.168.1.191','192.168.1.193']
env.hosts=['192.168.1.190']
env.port='22'
env.user='root'
env.password="Qwe21"
env.remote_package_dir='/usr/local'    
#备份函数
@task
@runs_once
def backup_task():
   print("<--------------开始备份新包-------------->")
   '''
   with lcd ("%s" %env.local_package_dir):
          local("tar zcvf %s-%s.tar.gz %s" %(env.local_package_name,env.time,env.local_package_name))
    '''
   print("<------------新包备份创建成功------------->")
@task
@runs_once
@hosts(['192.168.1.190'])
def up_nginx():
  #env.hosts=['192.168.1.190']
  local_nginx_dir="%s/nginx-col" %env.local_package_dir
  remote_nginx_dir="%s/nginx/soft" %env.remote_package_dir
  #if(os.path.exist
  run ("mkdir -p %s/nginx" %env.remote_package_dir)
  run ("mkdir -p %s" %remote_nginx_dir)
  
  for dirpath,dirnames,filenames in os.walk(local_nginx_dir):
    for file in filenames:
      fullpath=os.path.join(dirpath,file)
      put(fullpath,remote_nginx_dir)
      print("<---------已上传文件%s--------->" %fullpath)
  
#上传函数
@task
@hosts(['192.168.1.190'])
def put_task():
   print ("<-------------开始停止服务--------->")
   #run ('%s/%s/APIServer stop' %(env.local_package_dir,env.local_package_name))
   print   ("<-------------停止服务成功--------->")
   print("<-------------删除旧包------------>")
   #run  ('rm -fr %s/%s*' %(env.remote_package_dir,env.local_package_name))
   print  ("<-----------旧包删除成功----  ---->")
   
   print("<-----------开始上传新包---  ----->")
   run ("mkdir %s/nginx" %env.remote_package_dir)
   with lcd ("%s" %env.local_package_dir):
     #put('%s-%s.tar.gz' %(env.local_package_name,env.time),'%s/%s-%s.tar.gz' %(env.local_package_dir,env.local_package_name,env.time))
     put('%s/%s' %(env.local_package_dir,env.local_package_name),'%s/%s' %(env.remote_package_dir,env.local_package_name))
   print  ('<-----------新包上传成功---------->')
   
   #run ('tar zxf %s/%s-%s.tar.gz -C %s' %(env.local_package_dir,env.local_package_name,env.time,env.local_package_dir))
   print  ('<-------------解压成功------------>')
   
   #with cd ('%s/%s' %(env.remote_package_dir,env.local_package_name)): 
    #run ('./APIServer start')
   print ('<-------APIServer服务运行成功------->')
@task
def start():
   backup_task()
   put_task()
'''
if __name__=="__main__":    
  argc = len(sys.argv)   
  
  if argc != 3:    
      usage()    
      sys.exit(-1)    
  
#  first = sys.argv[1]  
#  second = sys.argv[2]  
'''
#up_nginx()